package test230609;

import java.util.Arrays;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/6/9 21:43
 * 132. 分割回文串 II
 * https://leetcode.cn/problems/palindrome-partitioning-ii/
 */
public class Solution04 {

    public int minCut(String s) {
        // 先存储 s[i, j] 是否为回文串的信息
        int n = s.length();
        boolean[][] judge = new boolean[n][n];
        for (int i = n - 1; i >= 0; --i) {
            for (int j = i; j < n; ++j) {
                if (s.charAt(i) == s.charAt(j)) {
                    judge[i][j] = i + 1 < j ? judge[i + 1][j - 1] : true;
                }
            }
        }
        // dp[i] 表示 s[0, i] 子串划分为回文串的最小分隔数
        // 状态初始化
        int[] dp = new int[n];
        Arrays.fill(dp, Integer.MAX_VALUE);
        // 动态规划过程
        for (int i = 0; i < n; ++i) {
            if (judge[0][i]) {
                dp[i] = 0;
            } else {
                for (int j = 1; j <= i; ++j) {
                    if (judge[j][i]) {
                        dp[i] = Math.min(dp[j - 1] + 1, dp[i]);
                    }
                }
            }
        }
        return dp[n - 1];
    }
}
